<template>
  <div class="data-analysis">
    <h2>数据分析</h2>
    <p>展示平台关键数据统计与趋势分析。</p>
    <div class="charts">
      <div class="chart-box">
        <h4>用户增长</h4>
        <svg width="220" height="100" viewBox="0 0 220 100">
          <polyline
            :points="userLinePoints"
            fill="none"
            stroke="#42b983"
            stroke-width="3"
          />
          <circle v-for="(v, i) in userGrowth" :key="i" :cx="i*35+20" :cy="100-(v.count-minUser)*70/rangeUser-10" r="4" fill="#42b983" />
        </svg>
        <div class="x-labels">
          <span v-if="userGrowth.length" :style="{left: '10px'}">{{ userGrowth[0].date }}</span>
          <span v-if="userGrowth.length" :style="{right: '10px', left: 'auto'}">{{ userGrowth[userGrowth.length-1].date }}</span>
        </div>
      </div>
      <div class="chart-box">
        <h4>设备活跃度</h4>
        <svg width="220" height="100" viewBox="0 0 220 100">
          <rect v-for="(v, i) in deviceActive" :key="i" :x="i*35+30" :y="100-v.count*0.7-10" width="20" :height="v.count*0.7" fill="#2d8cf0" />
        </svg>
        <div class="x-labels">
          <span v-if="deviceActive.length" :style="{left: '10px'}">{{ deviceActive[0].date }}</span>
          <span v-if="deviceActive.length" :style="{right: '10px', left: 'auto'}">{{ deviceActive[deviceActive.length-1].date }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
const userGrowth = ref([])
const deviceActive = ref([])

onMounted(async () => {
  const resUserGrowth = await fetch('http://localhost:3001/api/analysis/user-growth')
  userGrowth.value = await resUserGrowth.json()
  const resDeviceActive = await fetch('http://localhost:3001/api/analysis/device-active')
  deviceActive.value = await resDeviceActive.json()
})

const minUser = computed(() => Math.min(...userGrowth.value.map(v=>v.count)))
const maxUser = computed(() => Math.max(...userGrowth.value.map(v=>v.count)))
const rangeUser = computed(() => Math.max(1, maxUser.value-minUser.value))
const userLinePoints = computed(() => userGrowth.value.map((v,i)=>`${i*35+20},${100-(v.count-minUser.value)*70/rangeUser.value-10}`).join(' '))
</script>

<style scoped>
.data-analysis {
  padding: 2rem;
}
.charts {
  display: flex;
  gap: 2rem;
  margin-top: 1rem;
}
.chart-box {
  flex: 1;
  background: #f6f8fa;
  border-radius: 8px;
  padding: 1rem;
  text-align: center;
  position: relative;
}
.x-labels {
  position: absolute;
  bottom: 8px;
  left: 0;
  width: 100%;
  font-size: 0.9rem;
  color: #888;
  pointer-events: none;
}
.x-labels span {
  position: absolute;
  transform: translateY(0);
}
</style>
